package com.lsh.aspect;

import com.lsh.config.DatabaseContextHolder;
import com.lsh.dao.db1.UserMapper;
import com.lsh.dao.db2.BlogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/7/8 9:52 上午
 * @desc ：
 */
@Aspect
@Component
@Slf4j
public class ChangeSourceAspect {

    @Before("@annotation(com.lsh.anno.ChangeSource)")
    public void beforeOpt(JoinPoint joinPoint) {
        //根据实例类型动态切换数据源
        if(joinPoint.getTarget() instanceof UserMapper) {
            log.info("实例类型是：UserMapper");
            DatabaseContextHolder.setDataBaseType(DatabaseContextHolder.DataBaseType.DataBase1);
        }
        if(joinPoint.getTarget() instanceof BlogMapper) {
            log.info("实例类型是：BlogMapper");
            DatabaseContextHolder.setDataBaseType(DatabaseContextHolder.DataBaseType.DataBase2);
        }

    }

    /**
     * 结束之后清除
     */
    @After("@annotation(com.lsh.anno.ChangeSource)")
    public void afterOpt() {
        DatabaseContextHolder.clearDataSource();
        log.info("清除数据源");
    }


    public ChangeSourceAspect(){
        log.info("加载ChangeSourceAspect切面");
    }
}








